-module(server).
-export([start/0, kill/1]).
-import(werkzeug,[logging/2, get_config_value/2, timeMilliSecond/0, to_String/1]).

start() ->
	{_,Handle} = file:consult("../config/server.cfg"),
	{_,Lifetime} = get_config_value(lifetime, Handle),
	{_,ClientLifetime} = get_config_value(clientlifetime, Handle),
	{_,Servername} = get_config_value(servername, Handle),

	register(Servername, self()),

	Nachricht = lists:concat(["Server StartZeit: ", werkzeug:timeMilliSecond(), "| mit PID", to_String(self())]),
	werkzeug:logging("../NServer.log", Nachricht),

	timer:send_after(Lifetime*1000, self(), kill),
	queuemanager:start(),
	ClientManager = spawn(clientmanager, start, [ClientLifetime, queuemanager, self()]),	%msg an manager mit self() oder wk
	register(clientmanager, ClientManager),
	main(ClientManager, 1).

main(ClientManager, CurrentID) ->
	receive
		{getmsgid, ClientPID} ->
			ClientPID ! {nnr, CurrentID},%NachirchtenID vom Server holen
			main(ClientManager, CurrentID+1);
		{dropmessage, Nachricht} ->
			queuemanager ! {dropmessage, Nachricht}, %Nachricht = {Log_Nachricht, NachrichtenId}
			main(ClientManager, CurrentID);
		{getmessages, ClientPID} ->
			ClientManager ! {getmessages, ClientPID},
			main(ClientManager, CurrentID);
		kill -> kill(ClientManager)
	end.


kill(ClientManager) ->
	queuemanager:kill(),
	ClientManager ! kill,
	unregister(clientmanager),
	{_,Handle} = file:consult("../config/server.cfg"),
	{_,Servername} = get_config_value(servername, Handle),
	unregister(Servername).